import * as React from 'react';
import { Subscription } from 'rxjs';
import { Redirect } from 'react-router-dom';

import authService from '../../services/svc.auth';
import RealWorkSpacePage from './real-workspace-page';

import { User } from '../../models/user';

type StateType = {
  authenticated: boolean;
  load: boolean;
  user?: User;
};

export default class LoginPage extends React.Component {
  private subjects: Subscription | undefined;

  state: StateType = {
    authenticated: true,
    load: false,
  };

  componentDidMount() {
    this.subjects = authService.user.subscribe(({ authenticated, user }) => {
      this.setState({ authenticated, user, load: true });
    });
  }

  componentWillUnmount() {
    this.subjects.unsubscribe();
  }

  render() {
    if (!this.state.load) {
      return <div>加载中</div>;
    }

    if (this.state.authenticated) {
      return <RealWorkSpacePage user={this.state.user!!} />;
    } else {
      return <Redirect to="/" />;
    }
  }
}
